// pages/login/index.js
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    param: {
      account: '',
      password: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  bindAccountInput(e) {
    this.data.param.account = e.detail.value;
  },
  bindPwdInput(e) {
    this.data.param.password = e.detail.value;
  },
  login() {
    if (this.data.param.account == '') {
      wx.showToast({
        title: '账号为空',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.param.password == '') {
      wx.showToast({
        title: '密码为空',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    util.http({
      url: 'api/miniwechat/user/login',
      data: this.data.param,
      method: 'POST'
    }).then((data) => {
      console.log(data);
      wx.setStorage({
        key: 'userInfo',
        data: data.userinfo
      })
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }).catch((err) => {
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },
  goRegister() {
    wx.navigateTo({
      url: '/pages/register/index'
    })
  },
  getUserInfo(e) {
    console.log(e)
    wx.login({
      success(res) {
        console.log(res.code)

        if (res.code) {
          // 发起网络请求
          util.http({
            url: 'api/miniwechat/user/dologin',
            data: {
              code: res.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            },
            method: 'POST'
          }).then((data) => {
            console.log(12)
            wx.setStorage({
              key: 'userInfo',
              data: data.userinfo
            })
            wx.reLaunch({
              url: '/pages/index/index'
            })
          }).catch((err) => {
            wx.showToast({
              title: String(err),
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })

  }
})